package org.ddd.book.infrastructure.eventpublisher;

import com.google.common.eventbus.AsyncEventBus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

@Configuration
@Slf4j
public class EventBusConfiguration {

    @Bean("myAsyncEventBus")
    @SuppressWarnings("all")
    public AsyncEventBus createAsyncEventBus(@Qualifier("eventBusThreadPoolTaskExecutor") ThreadPoolTaskExecutor threadPool) {
        log.info("myAsyncEventBus=============");
        return new AsyncEventBus(threadPool);
    }

    @Bean("eventBusThreadPoolTaskExecutor")
    public ThreadPoolTaskExecutor eventBusThreadPoolTaskExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(10);
        threadPoolTaskExecutor.setMaxPoolSize(10);
        threadPoolTaskExecutor.setThreadFactory(new ThreadFactory() {
            private final AtomicInteger ct = new AtomicInteger(1);

            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("EventBus#" + ct.getAndIncrement());
                return thread;
            }
        });
        threadPoolTaskExecutor.initialize();
        return new ThreadPoolTaskExecutor();
    }

}
